package com.zxg.zbc.biz.util;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * 工具类
 */
public class Utils {
  public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

  /**
   * 得到显示时间
   * 
   * @return yyyy-MM-dd HH:mm:ss
   */
  public static String dateToString(Date date) {
    if (date == null) {
      return null;
    }
    return sdf.format(date);
  }

  /**
   * 根据显示时间得到日期
   * 
   * @param time
   *          yyyy-MM-dd HH:mm:ss
   * @return
   */
  public static Date stringToDate(String time) {
    if (StringUtils.isBlank(time)) {
      return null;
    }
    try {
      return sdf.parse(time);
    } catch (ParseException e) {
      e.printStackTrace();
      return new Date();
    }
  }

  /**
   * 将对象转成json串
   * 
   * @param obj
   * @return
   */
  public static String toJson(Object obj) {
    if (obj == null)
      return null;
    JSONObject result = new JSONObject();
    Field[] fields = obj.getClass().getDeclaredFields();
    for (int j = 0; j < fields.length; j++) {
      fields[j].setAccessible(true);
      // 字段名
      String key = fields[j].getName();
      // 字段类型
      String type = fields[j].getType().getName();
      try {
        // 字段值
        Object value = fields[j].get(obj);
        if (value != null) {
          // 如果是Date类型，转换成 yyyy-MM-dd HH:mm:ss
          if (type.equalsIgnoreCase("java.util.Date")) {
            value = Utils.dateToString((Date) value);
          }
          result.put(key, value.toString());
        } else {
          // 如果是Integer类型，转换成0
          if (type.equalsIgnoreCase("java.lang.Integer") || type.equalsIgnoreCase("java.lang.Long")) {
            value = 0;
            result.put(key, value.toString());
          }
        }
      } catch (Exception e) {
        System.out.println("object field transfer failed, but it`s ok. field = " + key + ", type = " + type);
      }
    }
    return JSONObject.toJSONString(result);
  }

  /**
   * 将json串转成对象
   * 
   * @param json
   * @param clazz
   * @return
   */
  @SuppressWarnings({ "rawtypes", "unchecked" })
  public static Object fromJson(String json, Class clazz) {
    if (StringUtils.isNotEmpty(json)) {
      return JSONObject.parseObject(json, clazz);
    }
    return null;
  }

  /**
   * 将newObj中待更新的字段值，填充到oldObj中做替换
   * 
   * @param oldObj
   * @param newObj
   * @return 更新后的obj
   */
  public static Object fillObj(Object oldObj, Object newObj) {
    Field[] oldf = oldObj.getClass().getDeclaredFields();
    Field[] newf = newObj.getClass().getDeclaredFields();
    for (int j = 0; j < oldf.length; j++) {
      try {
        newf[j].setAccessible(true);
        if (newf[j].get(newObj) != null) {
          oldf[j].setAccessible(true);
          oldf[j].set(oldObj, newf[j].get(newObj));
        }
      } catch (IllegalAccessException e) {
        System.out.println("object field transfer failed, but it`s ok. field = " + newf[j].getName() + ", type = " + newf[j].getType().getName());
      }
    }
    return oldObj;
  }

  public static String getRandomString(int length) { // length表示生成字符串的长度
    String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
      int number = random.nextInt(base.length());
      sb.append(base.charAt(number));
    }
    return sb.toString();
  }

  public static Long generateBillingId(Long userId) {
    String pre = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    if (userId == null)
      userId = (long) new Random().nextInt(1000);
    String post = userId + "";
    if (post.length() > 4)
      post = post.substring(0, 4);
    String s = pre + post;
    try {
      return Long.parseLong(s);
    } catch (Exception e) {
      return null;
    }
  }
  /**
   * 密码加密
   * 
   * @param salt
   * @param password
   * @return
   */
  public static String encryptPassword(String salt, String password) {
    return null;
  }

  public static Date plusDays(int num, Date assignDate) {
    if (assignDate == null) {
      return null;
    }
    // Date currentDate = assignDate;
    // System.out.println("现在的日期是：" + sdf.format(currentDate));
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(assignDate);
    calendar.add(Calendar.DATE, num);// num为增加的天数，可以改变的
    assignDate = calendar.getTime();
    // System.out.println("增加天数以后的日期：" + sdf.format(assignDate));
    return assignDate;
  }

  public static void main(String[] args) {

    Date assginDate = plusDays(30, new Date());
    System.out.println(assginDate);
    System.out.println(plusDays(100, assginDate));

    String salt = "123456";
    String password = encryptPassword(salt, "123456");

    System.out.println("salt=" + salt);
    System.out.println("password=" + password);
    System.out.println("random String=" + getRandomString(32));

    String mobile = "18900009999";
    System.out.println(mobile.substring(0, 3) + "****" + mobile.substring(7));

  }

}